<template>
  <el-dialog v-model="model" :width="width" :before-close="handleClose" destroy-on-close :top="top">
    <el-scrollbar :max-height="maxHeight">
      <div class="dialog-container">
        <slot></slot>
      </div>
    </el-scrollbar>
    <template #footer>
      <slot name="footer" v-if="$slots.footer"></slot>
      <div class="dialog-footer" v-if="!$slots.footer && footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">{{ confirmText }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
defineOptions({
  name: 'a-dialog'
})

interface Props {
  maxHeight?: string
  width?: number
  footer?: boolean
  top?: string
  confirm?: ((close: () => void) => void) | ((close: () => void) => Promise<void>) | undefined
  close?: () => void
  confirmText?: string
}

const model = defineModel<boolean>({ required: true })

const props = withDefaults(defineProps<Props>(), {
  maxHeight: '600px',
  width: 1000,
  top: '80px',
  footer: true,
  confirm: undefined,
  close: () => {},
  confirmText: '确认'
})

function handleClose() {
  model.value = false
  props.close()
}

function handleConfirm() {
  if (props.confirm) {
    props.confirm(() => {
      model.value = false
    })
  } else {
    model.value = false
  }
}
</script>
